
import WebSocket from 'ws';
import { SocksProxyAgent } from 'socks-proxy-agent';
import axios from 'axios';
import _ from 'lodash';
import utils from './utils/index.js';
const agent = new SocksProxyAgent(utils.Config.proxy);
const bot = new utils.Notice(utils.Config.bots.bian_3m);
(async () => {
  const { data } = await axios.get('https://fapi.binance.com/fapi/v1/premiumIndex', {
    httpAgent: agent,
    httpsAgent: agent,
    timeout: 10000,
  });
  const symbols = data
    .filter((item) => item.symbol.indexOf('_') === -1)
    .map((item) => `${item.symbol.toLowerCase()}_perpetual@continuousKline_3m`);
  const url = 'wss://fstream.binance.com/swift/stream';
  var socket = new WebSocket(url, { agent });
  socket.on('open', function open() {
    // 切割 symbols 数组为每个数组最多 200 个元素
    const chunks = _.chunk(symbols, 200);
    chunks.forEach((chunk, i) => {
      socket.send(JSON.stringify( {
        method: 'SUBSCRIBE',
        params: chunk,
        id: i + 1,
      }));
    });
  });
  socket.on('message', function (data) {
    try {
      const info = JSON.parse(data);
      if (info.stream && info.data.e === 'continuous_kline') {
        const symbol = info.data.ps;
        const o = info.data.k.o;
        const c = info.data.k.c;
        const t = new Date(info.data.k.t).Format("yyyy-MM-dd HH:mm");

        const rate = (c - o) / o * 100;
        // 张福大于 20% 提醒
        if (rate > 8) {
          console.log(symbol, `${symbol} ${rate.toFixed(2)}% ${t}`)
          bot.add(symbol, `${symbol} ${rate.toFixed(2)}% ${t}`);
        } else {
          bot.remove(symbol);
        }
      } else {
        console.log(new Date().toISOString(), ' message type:', info);
      }
    } catch (error) {
      console.error(new Date().toISOString(), 'Error parsing message:', error);
    }
  });
  socket.on('close', function() {
    // 退出
    console.log(new Date().toISOString(), 'WebSocket closed');
    process.exit(0);
  });
  bot.run();
})();

process.on('uncaughtException', (error) => {
  console.error(new Date().toISOString(), 'Uncaught Exception:', error);
  process.exit(0);
});


